

def test1(id=u'urn:uuid:0a2426c0-058b-45fe-9fb0-2382555391aa', scope=u'ftss:///root/public/nodes/corporate/main/index'):
    import Repo
    from nodetypes.models.Container import Container
    from myelin.server.lib.UriScopeResolver import UriScopeResolver
    
    repo = Repo.GetRepo()
    scope = scope
    model = Container.Initialize(
        repo.fetchResource(scope).getModel().driver,
        uriScopeResolver = UriScopeResolver(
            repo._driver
        )
    )
    res = Container.Retrieve(model, id, scope)
    
    return res, repo

def test1_2(id='urn:uuid:0a2426c0-058b-45fe-9fb0-2382555391aa', scope='ftss:///root/public/nodes/corporate/main/index'):
    import Repo
    from nodetypes.models.Container import Container
    from myelin.server.lib.UriScopeResolver import UriScopeResolver
    
    repo = Repo.GetRepo()
    scope = scope
    model = Container.Initialize(
        repo.getMergedModels([
            '/root/models/nodes/corporate/main/published.content',
            '/root/models/nodes/corporate/main/unpublished.content',
            '/root/models/nodes/corporate/main/archived.content',
        ])._driver,
        uriScopeResolver = UriScopeResolver(
            repo._driver
        )
    )
    res = Container.Retrieve(model, id, scope)
    
    return res, repo


def test2(
    resourceUri = 'ftss:///root/public/nodes/corporate/main/index',
    username = 'admin',
    passwd = '1q2w3e',
    domain = 'heusticalgos.com',
    rootUri=u'ftss:///root/accounts',
    domains={'heusticalgos.com':(u'HeusticAlgos',u'admins')}):
    from nodetypes.core.ft.Account import Account
    #from myelin.lib.StructDict import StructDict
    
    import Repo
    repo = Repo.GetRepo()
    
    #server = StructDict()
    models = {
        'accounts' : {
            'main' : ['/root/models/domains/heusticalgos.com/accounts',],
        },
        'app' : {
            'acls' : ['/root/models/acls',]
        },
    }
    
    acct = Account(repo, rootUri, domains, models)
    if username:
        import sha
        if not acct.login(domain, username, sha.new(passwd).hexdigest()):
            print "invalid login"
            return
    else:
        acct.loginAsGuest()
    acls = acct.retrieveAcls(resourceUri)
    return acct, acls, repo

def test3(domain='heusticalgos.com',agent='admin',passwd='Trustno1', node='ftss:///root/public/nodes/heusticalgos.com/www/topic1/rules/publish'):
    import sha
    acct, repo = test2()
    
    acct.login(domain,agent,sha.new(passwd).hexdigest())
    return acct, repo, acct.retrieveAcls(node)    
    

def test4(baseUri='ftss:///root/usr/i18n/en/US/themes/'):
    import Repo
    from myelin.server.servers.ft.http.processors.NodeTypeProcessor import FindThemes
    
    res = Repo.GetRepo().fetchResource(baseUri)
    return FindThemes(res), res

def doSearch(repo, account=None, params={'range':1,'keywords':'topic'}, sourceId='ftss:///root/public/nodes/heusticalgos.com/www/topic1/',root_uri='ftss:///root/public/nodes/demos/myelin/topic1'):
    import Repo
    from myelin.app.models.Container import Container
    from myelin.rdf.bindery import Model, ObjectTypes
    
    acls = account.retrieveAcls()
    
    range = params['range']
    if range == 1:
        model = Container.Retrieve(repo.getModel(), sourceId)            
    else:
        model = Container.Retrieve(repo.getModel(), defaults.root_uri)
        acls = account.acls.getNodeAcls(defaults.root_uri)
    
    keywords = params['keywords']
    filters = [
        lambda n: n.rdf_join('dcTitle').find(keywords) >= 0,
        lambda n: n.rdf_join('dcDescription').find(keywords) >= 0,
        lambda n: n.rdf_join('dcSubject').find(keywords) >= 0,
    ]
            
    results = []
    def _s(node, acls):
        for n in node.mContains: # translation, groupings
            a = acls.createChildAcls(n.rdf_value)
            if 'view' in a.base:
                for f in filters:
                    if f(n):
                        results.append(n)
                        break
            _s(n,a)
    _s(model, acls)
    return results, model

FTSS_ROOT_URI = 'ftss:///'
FTSS_ROOT_URI_LEN = len(FTSS_ROOT_URI)

def GetPaths(uri):
    if uri[-1] == '/':
        return map(
            lambda a: a + '/',
            uri[FTSS_URI_ROOT_LEN:].split('/')
        )
    
    uri = uri[FTSS_URI_ROOT_LEN:].split('/')
    return map(
        lambda a: a + '/',
        uri[:-1]
    ) + [uri[-1]]        

def ResetBase(uris):
    p = FTSS_URI_SCHEME
    for i in uris:
        p += i
        print p + '.acls'
        
def GetUrisReverse(uri):
    r = [FTSS_URI_ROOT]
    r_a = r.append
    
    if uri[-1] == '/':
        for i in uri[FTSS_URI_ROOT_LEN:-1].split('/'):
            r_a(r[-1] + i + '/')
    else:
        uri = uri[FTSS_URI_ROOT_LEN:].split('/')
        for i in uri[:-2]:
            r_a(r[-1] + i + '/')
        r_a(r[-1] + uri[-1])
        
    r.reverse()
    return r


def test_filter(d=None, filters=None, scope=None, flags={}, returnScope=False, conv=None):
    if d is None:
        res, repo = test1('urn:uuid:75a5e260-0860-407c-afc7-c7d160a226ff',scope='ftss:///root/public/nodes/corporate/main/topic1/index')
        d = res.rdf_dbDriver
    if filters is None:
        from Ft.Rdf.Drivers import OPERATORS, SET
        filters = (
            (SET.COMPLIMENT,OPERATORS.EQ,'http://purl.org/dc/elements/1.1/language',OPERATORS.EQ,'en-CA'),
            (SET.IDENTITY,OPERATORS.RIC,'http://purl.org/dc/elements/1.1/(title|subject|description)',OPERATORS.RIC,'t.*'),
            
            #(OPERATORS.LTE,'http://www.test.org/apples',OPERATORS.GT,'string2',FilterJoin.OR),
            #(OPERATORS.GT,'http://www.test.org/oranges',OPERATORS.LT,99L,FilterJoin.OR),
        )
    
    s = d.sizeBySetIntersection(filters, scope, flags)
    r = d.subjectsBySetIntersection(filters, scope, flags, returnScope, conv)
    
    return d, s, r
        
        
def GetPaths(uri):
    if uri[-1] == '/':
        return map(
            lambda a: a + '/',
            filter(None,uri[FTSS_URI_ROOT_LEN:-1].split('/'))
        )
    
    uri = uri[FTSS_URI_ROOT_LEN:].split('/')
    return map(
        lambda a: a + '/',
        uri[:-1]
    ) + [uri[-1]]        

FTSS_URI_ROOT = 'ftss:///'
FTSS_URI_ROOT_LEN = len(FTSS_URI_ROOT)

def GetScopes(uri, cache):
    uri = uri[0] == '/' and uri[1:].split('/') or \
        uri[FTSS_URI_ROOT_LEN:].split('/')
    
    s = FTSS_URI_ROOT
    r = [s].append
    for p in uri[:-1]:
        s += p + '/'
        r(s)
    if uri[-1]:
        r(s+uri[-1])
        i = 0
    else:
        i = 1
            
    r = r.__self__
    r.reverse()
    c = cache.get
    for p in r:
        a = c(p)
        if a is not None:
            a = a.copy()            
            uri.reverse()
            uri = uri[:i]
            uri.reverse()            
            r = r[:i]
            break
        i += 1
    else:
        p = FTSS_ROOT_URI
        a = set()
        
    for i in uri[:-1]:
        p += '(?:\.|' + i + '/'
    if uri[-1]:
        p += '/(?:\.|' + uri[-1] + '\.' + ')'*len(uri) + 'acls'
    else:
        p += '\.' + ')'*(len(uri)-1) + 'acls'
        
    r.reverse()
    return r, p, a


def test_graph(id='urn:uuid:649f445b-14ec-4f35-8f2e-cc76525a4bd0', scope='ftss:///root/servers/heusticalgos.com/www/nodes/help/graphs/ontologies/index'):
    import Repo
    from nodetypes.models.Graph import Graph
    from myelin.server.lib.UriScopeResolver import UriScopeResolver
    
    repo = Repo.GetRepo()
    scope = scope
    model = Graph.Initialize(
        repo.fetchResource(scope).getModel()._driver,
        uriScopeResolver = UriScopeResolver(
            repo._driver
        )
    )
    res = Graph.Retrieve(model, id, scope)
    
    return res, repo